<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="keyword"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group>
      <van-cell
        :title="item"
        icon="search"
        v-for="item in sugList"
        :key="item"
      ></van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录"></van-cell>
      <van-cell :title="item" v-for="item in history" :key="item">
        <van-icon name="close" @click="delFn(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import { setStorageHistory, getStorageHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      keyword: '',
      sugList: [], // 搜索列表
      history: getStorageHistory() // 历史记录
    }
  },
  methods: {
    // 搜索匹配
    async onInput() {
      if (!this.keyword) return
      const { data } = await getSuggest(this.keyword)
      this.sugList = data.options
    },
    // 添加到历史记录
    onSearch() {
      this.history = this.history.filter((item) => item !== this.keyword)
      this.history.unshift(this.keyword)
      setStorageHistory(this.history)
    },
    // 删除历史记录
    delFn(item) {
      this.history = this.history.filter((v) => v !== item)
      setStorageHistory(this.history)
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-nav-bar .van-icon {
  color: #fff;
}
</style>
